package com.probox.common.entity.service.wechat.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import com.probox.common.core.constant.CachePrefix;
import com.probox.common.core.constant.Constants;
import com.probox.common.core.utils.DateUtils;
import com.probox.common.redis.service.RedisService;
import com.probox.customer.api.domain.CustomerInfoAccountVo;
import com.probox.wechat.api.domain.WechatAuthorizationInfoVo;
import com.probox.common.entity.service.wechat.WechatPlatformService;
import com.probox.common.entity.domain.wechat.vo.AllworkAuthorizationInfoVo;
import com.probox.common.entity.domain.wechat.vo.AuthorizationInfoVo;
import com.probox.common.entity.domain.wechat.vo.WechatTicketVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.probox.common.entity.mapper.wechat.WechatAuthorizationInfoMapper;
import com.probox.common.entity.domain.wechat.WechatAuthorizationInfo;
import com.probox.common.entity.service.wechat.IWechatAuthorizationInfoService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 授权信息Service业务层处理
 *
 * @author usoft
 * @date 2021-07-06
 */
@Service
@Transactional
public class WechatAuthorizationInfoServiceImpl extends ServiceImpl<WechatAuthorizationInfoMapper, WechatAuthorizationInfo> implements IWechatAuthorizationInfoService
{
    @Autowired
    private WechatAuthorizationInfoMapper wechatAuthorizationInfoMapper;

    @Autowired
    private WechatPlatformService wechatPlatformService;

    @Autowired
    private WechatMiniServiceImpl wechatMiniService;

    @Autowired
    private RedisService redisService;

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());


    @Override
    public WechatAuthorizationInfoVo getAuthorizationInfo(String authorizerAppid) {
        String key = CachePrefix.WECHAT_AUTHORIZERINDO_INFO+authorizerAppid;
        WechatAuthorizationInfoVo authorizerindoInfo = redisService.getCacheObject(key);
        if(ObjectUtil.isEmpty(authorizerindoInfo)){
            WechatAuthorizationInfo wechatAuthorizationInfo = wechatAuthorizationInfoMapper.selectById(authorizerAppid);
            if (wechatAuthorizationInfo==null){
                return null;
            }
//            WechatAuthorizationInfoVo wechatAuthorizationInfoVo = new WechatAuthorizationInfoVo();
            authorizerindoInfo = new WechatAuthorizationInfoVo();
            BeanUtils.copyProperties(wechatAuthorizationInfo, authorizerindoInfo);
            redisService.setCacheObject(key,authorizerindoInfo,5L, TimeUnit.MINUTES);
        }

        return authorizerindoInfo;
    }

    @Override
    public CustomerInfoAccountVo wechatAllworkLogin(CustomerInfoAccountVo customerInfoAccountVo) {
        String wechatAllWorkLogin = CachePrefix.WECHAT_ALLWORK_LOGIN+customerInfoAccountVo.getAppid();
        AllworkAuthorizationInfoVo vo  = redisService.getCacheObject(wechatAllWorkLogin);
        if(ObjectUtil.isEmpty(vo)){
            logger.info("请求参数code=>"+customerInfoAccountVo.getCode()+",appid:"+customerInfoAccountVo.getAppid());
            String rst =  HttpUtil.get("https://api.weixin.qq.com/sns/oauth2/access_token?appid="+Constants.gzh_app_id+"&secret="+Constants.gzh_app_secret+"&code="+customerInfoAccountVo.getCode()+"&grant_type=authorization_code");
            logger.info("通过 code 换取 access_token返回值:"+rst);
            JSONObject obj = JSONObject.parseObject(rst);
            String errcode =  obj.getString("errcode");
            if(!"40029".equals(errcode)){
                vo = JSON.parseObject(rst, AllworkAuthorizationInfoVo.class);
                redisService.setCacheObject(wechatAllWorkLogin,vo,Long.parseLong(vo.getExpires_in())-100, TimeUnit.SECONDS);
            }
        }
        //通过网页授权 access_token 获取用户基本信息
        String userinfoRst =  HttpUtil.get("https://api.weixin.qq.com/sns/userinfo?access_token="+vo.getAccess_token()+"&openid="+vo.getOpenid()+"&lang=zh_CN");
        logger.info("通过网页授权 access_token 获取用户基本信息返回:"+userinfoRst);
        CustomerInfoAccountVo infoAccountVo = JSON.parseObject(userinfoRst, CustomerInfoAccountVo.class);
        return infoAccountVo;
    }


    /**
     *  获取jsapi_ticket
     * @return
     */
    @Override
    public String getTicket(String appId) {
        String wechat_ticket_info = CachePrefix.WECHAT_TICKET_INFO+"_"+appId;
        WechatTicketVo rst = redisService.getCacheObject(wechat_ticket_info);
        logger.info("getTicket from cache {}",rst);
        if (rst == null) {
            String access = getAccessToken(appId);
            logger.info("getTicket access cache {}",access);
            if (!StringUtils.isEmpty(access)) {
                rst = getTicketByAccessToken(access);
                if (rst != null) {
                    redisService.setCacheObject(wechat_ticket_info,rst, Long.parseLong(String.valueOf(rst.getExpires_in()-60)),TimeUnit.SECONDS);
                    return rst.getTicket();
                }
            }
        }
        if (rst != null) {
            return rst.getTicket();
        }else {
            return null;
        }
    }

    /**
     * 获取平台的accessToken info
     * @return
     */
    //private static String wechat_access_token_info = CachePrefix.WECHAT_ACCESS_TOKEN_INFO;
    private  String getAccessToken(String appId) {
        String wechat_access_token_info = CachePrefix.WECHAT_ACCESS_TOKEN_INFO+"_"+appId;
        String access_token = redisService.getCacheObject(wechat_access_token_info);
        if (StringUtils.isEmpty(access_token)) {
            WechatAuthorizationInfoVo wechatAuthorizationInfoVo = getAuthorizationInfo(appId);
            if (wechatAuthorizationInfoVo != null) {
                AuthorizationInfoVo vo = wechatPlatformService.getApi_authorizer_token(wechatPlatformService.getApiComponentToken(), appId, wechatAuthorizationInfoVo.getAuthorizerRefreshToken());
                if (vo != null) {
                    access_token = vo.getAuthorizer_access_token();
                    redisService.set(wechat_access_token_info,access_token,30L,TimeUnit.MINUTES);
                }
                //access_token = wechatPlatformService.getAuthorizationInfoAccessToken(appId);
            }
        }

        //String access_token = wechatPlatformService.getApiComponentToken();
        /*
        String data = redisService.getCacheObject(wechat_access_token_info);
        if (StringUtils.isEmpty(data)) {
            String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+WechatPlatformService.appId+"&secret="+WechatPlatformService.appSecret;
            String rst = HttpUtil.get(url);
            logger.info(" getAccessToken rst:{}",rst);
            if (!StringUtils.isEmpty(rst)) {
                WechatTicketVo vo = JSONObject.parseObject(rst, WechatTicketVo.class);
                access_token = vo.getAccess_token();
                if (!StringUtils.isEmpty(access_token))
                    redisService.setCacheObject(wechat_access_token_info,rst,Long.parseLong(String.valueOf(vo.getExpires_in()-60)),TimeUnit.SECONDS);
            }
        }else {
            WechatTicketVo vo = JSONObject.parseObject(data, WechatTicketVo.class);
            access_token = vo.getAccess_token();
        }*/
        return access_token;
    }

    /**
     * 获取签名票据
     * @param access_token
     * @return
     */
    private  WechatTicketVo getTicketByAccessToken(String access_token) {
        String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+access_token+"&type=jsapi";
        String rst = HttpUtil.get(url);
        logger.info(" getTicket rst:{}",rst);
        if (rst != null) {
            WechatTicketVo vo = JSONObject.parseObject(rst, WechatTicketVo.class);
            return vo;
        }
        return null;
    }

    /**
     * 签名
     * @param jsapi_ticket
     * @param timestamp
     * @param noncestr
     * @param url
     * @return
     */
    @Override
    public String sign(String jsapi_ticket, String timestamp, String noncestr, String url) {
        String str = "jsapi_ticket="+jsapi_ticket+"&noncestr="+noncestr+"&timestamp="+timestamp+"&url="+url;
        return SHA1(str);
    }

    /**
     * 加密
     * @param decript
     * @return
     */
    private  String SHA1(String decript) {
        try {
            MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1");
            digest.update(decript.getBytes());
            byte messageDigest[] = digest.digest();
            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 根据商户id查询域名
     * @param uid
     * @return
     */
    @Override
    public String getDomainName(Long uid){
        String domainName ="";
        QueryWrapper<WechatAuthorizationInfo> queryWrapper =new QueryWrapper<>();
        queryWrapper.eq("MERCHANT_ID",uid);
        List<WechatAuthorizationInfo> wechatAuthorizationInfos = wechatAuthorizationInfoMapper.selectList(queryWrapper);
        if(ObjectUtil.isNotEmpty(wechatAuthorizationInfos)){
            if(ObjectUtil.isNotEmpty(wechatAuthorizationInfos.get(0))){
                domainName = wechatAuthorizationInfos.get(0).getDomainName();
            }
        }
        return domainName;
    }

}
